package com.csjbot.weedle_auto.app.automatic

import android.app.Activity
import com.csjbot.weedle_auto.SerialServer.util.bean.SerialPortEvents
import com.csjbot.weedle_auto.SerialServer.util.bean.SerialPortOtherBean
import com.csjbot.weedle_auto.Slam.events.RobotStatusUpdateEvent
import com.csjbot.weedle_auto.app.BaseApplication
import com.csjbot.weedle_auto.app.automatic.bean.MainItemBean
import com.csjbot.weedle_auto.app.automatic.bean.SerialBean
import com.csjbot.weedle_auto.app.automatic.bean.ShowResultBean
import com.csjbot.weedle_auto.file.constants_util.Constants
import com.csjbot.weedle_auto.fragment.bean.AdioCheckBean
import com.csjbot.weedle_auto.fragment.bean.StationBean
import com.csjbot.weedle_auto.fragment.util.ShareConstants
import com.csjbot.weedle_auto.util.Csjlogger
import com.csjbot.weedle_auto.util.DataUtil
import com.csjbot.weedle_auto.util.SharePreferenceTools
import com.csjbot.weedle_auto.util.TimeUtil
import java.util.*

/**
 * author : chenqi.
 * e_mail : 1650699704@163.com.
 * create_time : 8/21/17.
 */

class MainPresenter(private val view: AutoMaticContract.view, private val activity: Activity) : AutoMaticContract.presenter {
    private val title: MutableList<MainItemBean>
    private var mainItemBean: MainItemBean? = null
    private val serial: SerialBean
    private var times = 1

    private var stationBean: StationBean? = null
    private var sharePreferenceTools: SharePreferenceTools? = null
    private var adioCheckBean: AdioCheckBean? = null
    private var th: TaskThread? = null

    init {
        title = ArrayList()
        serial = SerialBean()
        sharePreferenceTools = SharePreferenceTools(activity)
        adioCheckBean = AdioCheckBean()
        stationBean = StationBean()
    }


    override fun start() {}

    override fun setList() {
        view.showList(title)
    }

    /**
     * 串口数据来源
     *
     * @param data
     */
    override fun setText(data: String) {
        mainItemBean = MainItemBean(data, "没有数据", false)
        title.add(mainItemBean!!)
    }


    /**
     * 利用time测试次数来判断是否通过
     *
     * @param events
     * @param times
     */
    override fun setSerialInfor(events: SerialPortEvents, times: Int) {
//        Csjlogger.info("chenqi setSerialInfor {} " + events.event!!)
        if (events.event == SerialPortEvents.Event.TOUCH) {
            if (events.m is Int) {
                view.updateTouch(TimeUtil.currenTime + "\r\n" + events.m.toString() + "\r\n", Determine(events.m.toString()))
                adioCheckBean!!.isTouch = Determine(events.m.toString())
                adioCheckBean!!.touch_text = events.m.toString()
            }
        } else if (events.event == SerialPortEvents.Event.SNDOWN) {
            if (events.m is String) {
                serial.snDown = events.m as String
                view.updateSnDown(TimeUtil.currenTime + "\r\n" + events.m.toString() +
                        "\r\n", Determine(events.m as String))
                adioCheckBean!!.isSn_down = Determine(events.m.toString())
                adioCheckBean!!.sn_down_text = events.m.toString()
            }
        } else if (events.event == SerialPortEvents.Event.SNUP) {
            if (events.m is String) {
                view.updateSnUp(TimeUtil.currenTime + "\r\n" + events.m.toString() + "\r\n", Determine(events.m as String))
                adioCheckBean!!.isSn_up = Determine(events.m.toString())
                adioCheckBean!!.sn_up_text = events.m.toString()
            }
        } else if (events.event == SerialPortEvents.Event.OTHER) {
            if (events.m is SerialPortOtherBean) {
                val s = events.m as SerialPortOtherBean
                Csjlogger.info("chenqi setSerialInfor {}1 " + s.toString2())
                val bt = DataUtil.isIBean(s.infrared)
                val pbt = DataUtil.isPINR(s.platE_INFRARED)
                val ss = ShowResultBean()
                ss.setData(pbt[0], pbt[1], bt[0], bt[1], bt[2], bt[3], bt[4])
                Csjlogger.info("chenqi serialPortListener in2 {}" + s.toString2())
                adioCheckBean!!.showResultBean = ss.toString()
                adioCheckBean!!.serialPortOtherBean = s.toString()
                if (DataUtil.isPassToDataFromOther(s.scr, s.infrared, s.platE_INFRARED, s.oa)) {
                    view.updateOther(ss.toString() + s.toString(), true)
                } else {
                    view.updateOther(ss.toString() + s.toString(), false)
                }
            }
        }
        sharePreferenceTools!!.putModel(Constants.CHECKINFOR, adioCheckBean)
    }


    override fun testTimes(times: Int) {
        this.times = times
    }

    override fun actionTask() {
        view.stopShowActionButton()
        BaseApplication.instance.agent.connectTo("192.168.11.1", 1445)
        th = TaskThread()
        if (times <= 0) {
            times = 1
            th!!.start()
        } else
            th!!.start()

    }


    override fun actionSlam() {}

    override fun connectLostSlam() {
        connect = false
        stationBean = StationBean()
        stationBean!!.iso = "slam没有连接！"
        view.showSlamStatus(stationBean!!.toString2(), false)
        sharePreferenceTools!!.putModel(Constants.SLAMSTATIONBEAN, stationBean)
        view.slamLost()
    }

    private var connect = false

    override fun connectSlam() {
        connect = true
        ShareConstants.GetAgentUpdate(BaseApplication.instance.agent)
        stationBean!!.connect = true
        sharePreferenceTools!!.putModel<StationBean>(Constants.SLAMSTATIONBEAN, stationBean)
    }

    override fun slamStatus(event: RobotStatusUpdateEvent) {
        Csjlogger.info("chenqi slamStatus{}" + event)
        stationBean!!.isCharge = event.isCharging
        stationBean!!.power = event.batteryPercentage
        if (event.batteryPercentage != 0 && connect) {
            stationBean!!.iso = "状态正确！"
            view.showSlamStatus(stationBean!!.toString(), true)
        } else if (connect && event.batteryPercentage == 0) {
            stationBean!!.iso = "电池状态不正确！"
            view.showSlamStatus(stationBean!!.toString2(), false)
        } else {
            stationBean!!.iso = "slam没有连接！"
            view.showSlamStatus(stationBean!!.toString2(), false)
        }
        sharePreferenceTools!!.putModel<StationBean>(Constants.SLAMSTATIONBEAN, stationBean)
    }

    override fun getResult() {
        adioCheckBean = sharePreferenceTools!!.getModel(Constants.CHECKINFOR, AdioCheckBean::class.java)
        val all = adioCheckBean!!.toString() + stationBean!!.toString()
        sharePreferenceTools!!.putString(Constants.ALLINFOR, all)
        view.showResult(all)
    }

    override fun closeTask() {
        BaseApplication.instance.agent.disconnect()
    }

    override fun stopThread() {
        times = 0
    }

    override fun clear() {
        sharePreferenceTools!!.putModel(Constants.SLAMSTATIONBEAN, StationBean())
        sharePreferenceTools!!.putModel(Constants.CHECKINFOR, AdioCheckBean())
        view.clearResult()
    }

    inner class TaskThread : Thread() {
        override fun run() {
            while (times > 0) {
                BaseApplication.instance.serial.putSnUp()
                BaseApplication.instance.serial.putOtherOrder()
                BaseApplication.instance.serial.putSnDown()
                try {
                    Thread.sleep(2000)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
                times--
            }
            view.testStop("serial")
            view.openShowActionButton()
        }
    }


    private fun Determine(msg: String?): Boolean {
        return msg != null
    }
}
